package controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import persistence.GruposDao;
import persistence.GruposDaoImpl;

import model.Login;

@WebServlet("/grupos")
public class GruposServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public GruposServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String erro = "";
		String mensagem = "";
		String url = "grupos.jsp";
		List<Login> lista = new ArrayList<Login>();
		String ra = request.getParameter("ra").toString().trim();
		String integr1 = request.getParameter("integrante1").toString().trim();
		String integr2 = request.getParameter("integrante2").toString().trim();
		String integr3 = request.getParameter("integrante3").toString().trim();
		String integr4 = request.getParameter("integrante4").toString().trim();
		Login lRa = new Login();
		lRa.setSenha(ra);
		lista.add(lRa);
		if (!integr1.equals("")){
			Login l1 = new Login();
			l1.setSenha(integr1);
			lista.add(l1);
		}
		if (!integr2.equals("")){
			Login l2 = new Login();
			l2.setSenha(integr2);
			lista.add(l2);
		}
		if (!integr3.equals("")){
			Login l3 = new Login();
			l3.setSenha(integr3);
			lista.add(l3);
		}
		if (!integr4.equals("")){
			Login l4 = new Login();
			l4.setSenha(integr4);
			lista.add(l4);
		}
		
		GruposDao grDao = new GruposDaoImpl();
		try {
			 mensagem = grDao.cadastraGrupo(lista);
			 url = "cadastro.jsp";
		} catch (SQLException e) {
			erro = e.getMessage();
		}
		
		request.setAttribute("mensagem", mensagem);
		request.setAttribute("erro", erro);
		request.setAttribute("login", lRa);
		RequestDispatcher view = request.getRequestDispatcher(url);
		view.forward(request, response);
	}

}
